<template>
  <view class="overall">
    <view class="content">
      <!-- 日历 -->
      <view style="background-color: white;margin-top: -80px;" class="calendar" @touchstart="handleTouchStart"
        @touchend="handleTouchEnd">
        <view class="header"></view>
        <view class="days-of-week">
          <view v-for="day in daysOfWeek" :key="day">{{ day }}</view>
        </view>
        <view class="dates">
          <view v-for="(date, index) in dates" :key="index"
            :class="{ 'not-current-month': date.month !== month, 'today': date.isToday }"
            :style="date.day == myday ? 'background-color:#A6A6A6;' : ''" @click="checked(date.day)">
            <view>{{ date.day }}</view>
          </view>
        </view>
      </view>
      
      <wd-status-tip image-size="60" v-if="doctor == null" image="content" tip="暂无内容" />
      
      <view class="tiem" v-if="doctor != null">
        <view v-for="(item, index) in office" :key="index" class="doctor-item">
          <view style="background-color: white;margin-top: 10px; position: relative;" 
                v-if="item.office && item.office.length > 0">
            <view class="doctor">
              <view class="doctor-avatar-container">
                 <image :src="apiUrl + item.doctor.avatar" mode="aspectFill"></image>
              </view>
              <view class="doctor-info">
                <view class="doctor-basic">
                  <view>{{ item.doctor.name }}</view>
                  <view>{{ item.doctor.duties }}</view>
                </view>
                <view class="doctor-skills">
                  {{ item.doctor.good }}
                </view>
              </view>
            </view>
            
            <!-- 价格和预约按钮移至右侧 -->
            <view class="booking-info" style="position: absolute; right: 15rpx; bottom: 15rpx;">
              <view class="price">￥ {{ item.doctor.money }}</view>
              <view class="booking-btn" @click="handleBooking(item, item.office[0])">预约</view>
            </view>
            
            <!-- 分隔线 -->
            <view class="divider" style="margin-top: 20rpx;"></view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref, watch } from 'vue';
import { doctorList, doctorSchedule, doctorDetails, card } from '@/api/index'; // 导入封装的card接口
import { BASE_API_URL } from '@/utils/config'; // 导入配置
// 定义计算属性，简化模板中的使用
const apiUrl = computed(() => BASE_API_URL);
// 响应式数据
const contentList = ref([]); // 用于内容展示
const doctor = ref([]);  // 医生信息
const office = ref([]);   // 医生办公信息
const name = ref<any>(null);  // 科室信息
const topHeight = ref(0);  // 用于存储动态计算的top高度
const availableNumbers = ref({}); // 存储每个医生的可用号源数量

// 在组件挂载时获取设备信息
onMounted(() => {
  const systemInfo = uni.getSystemInfoSync();
  const navBarHeight = systemInfo.statusBarHeight;  // 获取状态栏的高度
  topHeight.value = navBarHeight + 44;  // 导航栏高度加50px
  console.log('导航栏高度:', navBarHeight);
  console.log('动态计算的top高度:', topHeight.value);
});

// 获取科室数据
uni.getStorage({
  key: 'selectedDepartment',
  success: (res) => {
    console.log('读取存储数据:', res.data);
    name.value = res.data; // 将科室数据赋值给name
  },
  fail: (err) => {
    console.error('读取存储失败', err);
  }
});

// 请求医生信息
async function fetchDoctorData(departmentId: number) {
  try {
    const response = await doctorList({
      depart_id: departmentId
    });

    if (response.data) {
      doctor.value = response.data;

      const newmonth = (month.value + 1).toString().padStart(2, '0');
      const newday = day.value.toString().padStart(2, '0');
      const formattedDate = `${year.value}-${newmonth}-${newday}`;

      if (response.data != null) {
        const mergedArray = await Promise.all(
          response.data.map(async (item) => {
            const schedulingResponse = await doctorSchedule({
              depart_id: item.depart_id,
              date: formattedDate,
            });

            let officeData = schedulingResponse.data;
            officeData = Array.isArray(officeData) ? officeData.sort((a, b) => a.time - b.time) : [officeData];

            await fetchAvailableNumbers(item.id);
            
            return {
              doctor: item,
              office: officeData,
            };
          })
        );

        office.value = mergedArray;
      }
    }
  } catch (error) {
    console.error('获取医生信息失败:', error);
  }
}

// 获取可用号源数量
async function fetchAvailableNumbers(doctorId: number) {
  try {
    const response = await doctorDetails({
      doctor_id: doctorId
    });
    
    if (response.data && response.data.children) {
      availableNumbers.value = {
        ...availableNumbers.value,
        [doctorId]: response.data.children.length
      };
    }
  } catch (error) {
    console.error(`获取医生ID=${doctorId}的可用号源失败:`, error);
  }
}

// 监听日期选择变化，重新请求数据
watch(myday, () => {
  if (name.value && name.value.id) {
    fetchDoctorData(name.value.id);
  }
});

// 初始化事件，获取并加载科室和医生信息
async function event() {
  uni.getStorage({
    key: 'selectedDepartment',
    success: function (res) {
      console.log(res.data);
      name.value = res.data; // 获取存储的科室信息
      fetchDoctorData(res.data.id); // 使用存储的id获取医生数据
    }
  });
}

event();

// 日历相关
const year = ref(new Date().getFullYear());
const month = ref(new Date().getMonth());
const daysOfWeek = ['日', '一', '二', '三', '四', '五', '六'];
const day = ref(new Date().getDate());
const myday = ref(null);

const dates = computed(() => {
  const today = new Date().getDate();
  const firstDayOfMonth = new Date(year.value, month.value, 1).getDay();
  const totalDaysInMonth = new Date(year.value, month.value + 1, 0).getDate();
  const datesArray = [];
  for (let i = 1; i <= totalDaysInMonth; i++) {
    const isToday = i === today && month.value === new Date().getMonth();
    datesArray.push({ day: i, month: month.value, isToday });
  }
  return datesArray;
});

const checked = (day) => {
  const today = new Date();
  const selectedDate = new Date(year.value, month.value, day); // 用户点击的日期

  // 如果选中的日期是过去的日期
  if (selectedDate < today) {
    uni.showToast({
      title: '无法选择过去的日期',
      icon: 'none',
      duration: 2000
    });
  } else {
    myday.value = day; // 选择日期
  }
};

// 返回上一页
const returns = () => {
  console.log('返回上一页');
}

// 处理预约逻辑 - 修改后所有医生都可以预约
const handleBooking = async (doctorItem, scheduleItem) => {
  try {
    // 从本地存储获取用户信息
    const userInfo = uni.getStorageSync('user');
    if (!userInfo || !userInfo.data || !userInfo.data.id) {
      uni.showToast({
        title: '用户信息不存在',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    // 打印请求参数
    const requestData = {
      user_id: userInfo.data.id
    };
    console.log('请求参数:', requestData);
    
    // 调用封装的接口
    const response = await card(requestData);
    
    // 打印接口响应数据
    console.log('接口响应数据:', response);
    
    // 检查接口返回数据格式
    if (!response.data || !response.data.data || !Array.isArray(response.data.data) || response.data.data.length === 0) {
      uni.showToast({
        title: '获取用户余额信息失败',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    // 获取用户余额和医生价格
    const userBalance = response.data.data[0].money;
    const doctorPrice = parseFloat(doctorItem.doctor.money);
    
    console.log('用户余额:', userBalance);
    console.log('医生价格:', doctorPrice);
    
    // 检查余额是否充足
    if (userBalance === null || userBalance === undefined || userBalance === '' || parseFloat(userBalance) < doctorPrice) {
      uni.showToast({
        title: '余额不足，请先充值',
        icon: 'none',
        duration: 2000
      });
      uni.navigateTo({
        url: '/pages/payment/payment',
      });
      return;
    }
    
    // 余额充足，继续处理预约流程
    navigateToBookingPage(doctorItem, scheduleItem);
  } catch (error) {
    console.error('请求接口失败:', error);
    uni.showToast({
      title: '网络请求失败，请稍后再试',
      icon: 'none',
      duration: 2000
    });
  }
}

// 跳转到预约页面
const navigateToBookingPage = (doctorItem, scheduleItem) => {
  const bookingData = {
    doctor: doctorItem.doctor,
    schedule: scheduleItem,
    availableNumber: availableNumbers.value[doctorItem.doctor.id] || 0
  };
  uni.setStorageSync('bookingData', JSON.stringify(bookingData)); // 保存选中的医生和排班信息
  console.log('Stored Booking Data:', bookingData);
  uni.navigateTo({
    url: `/pages/sure/sure`
  });
};
</script>

<style scoped>
/* 样式部分保持不变 */
.overall {
  width: 100%;
  padding-bottom: 20rpx;
}

.title {
  width: 100%;
  height: 5rem;
  background-color: #00DACA;
  color: white;
  display: flex;
  align-items: center;
  position: fixed;
  top: 0;
}

.name {
  display: flex;
  align-items: center;
  font-weight: bold;
  font-size: 42rpx;
  line-height: 3rem;
  margin-left: 3%;
  margin-top: 30px;
}

.name>view {
  margin-left: 30rpx;
}

.content {
  width: 94%;
  margin: 180rpx 3%;
}

.calendar {
  min-height: 35vh;
  border-bottom: #EBEBEB 6rpx solid;
}

.days-of-week {
  width: 100%;
  display: flex;
  border-bottom: #EBEBEB 5rpx solid;
}

.days-of-week>view {
  width: 92rpx;
  height: 60rpx;
  margin: 5rpx 7rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.dates {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}

.dates>view {
  width: 12.5%;
  height: 70rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 4rpx 7rpx;
}

.today {
  color: #00DACA;
}

.tiem {
  width: 100%;
}

.doctor-item {
  margin-bottom: 15rpx;
}

.doctor {
  width: 100%;
  min-height: 140rpx;
  display: flex;
  justify-content: center;
  padding: 20rpx 15rpx;
  background-color: white;
  position: relative;
}

.doctor-avatar-container {
  width: 100rpx;
  height: 100rpx;
  background-color: #E5E5E5;
  border-radius: 10000rpx;
  overflow: hidden; /* 确保图片不会超出容器 */
}

.doctor-avatar-container image {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 保持图片比例，覆盖容器 */
}

.doctor-info {
  width: 72%;
  margin-left: 5%;
  font-size: 28rpx;
}

.doctor-basic {
  display: flex;
  margin-bottom: 15rpx;
}

.doctor-basic > view:first-child {
  font-weight: bold;
  padding-right: 40rpx;
}

.doctor-basic > view:last-child {
  border-left: 5rpx #EEEEEE solid;
  padding-left: 20rpx;
  color: #A6A6A6;
}

.doctor-skills {
  width: 90%;
  font-size: 28rpx;
  color: #A6A6A6;
  word-wrap: break-word;
  overflow: hidden;
  height: 20px;
}

.booking-info {
  display: flex;
  align-items: center;
}

.price {
  color: #EC5C28;
  margin-right: 15rpx;
  font-size: 32rpx;
}

.booking-btn {
  background-color: #2EC7C9;
  color: white;
  width: 100rpx;
  padding: 10rpx 5rpx;
  border-radius: 10rpx;
  white-space: nowrap;
  text-align: center;
  font-size: 28rpx;
}

.name>image {
  width: 20px;
  height: 20px;
}

/* 分隔线样式 */
.divider {
  height: 1rpx;
  background-color: #E5E5E5;
  width: 100%;
}
</style>